package com.lance.answer.question_export;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.lance.answer.dto.ExamPaperTitleItemVM;
import com.lance.answer.dto.LearnSection;
import com.lance.answer.dto.QuestionEditItemVM;
import com.lance.answer.dto.QuestionEditRequestVM;
import com.lance.answer.enums.QuestionTypeEnum;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author yixun
 * @version 2.0.0
 * @description
 * @date 2021-06-07 23:45
 * @since 2.0.0
 */
public class AnswerExport {

    public static void main(String[] args) throws IOException {
       // export("人体解剖生理学");
        export("人体解剖生理学");
    }

    public static void export(String subjectCode) throws IOException {
        //generate
        List<ExamPaperTitleItemVM> titleItems = generate(subjectCode);
        //save questions_bak
        List<Map<String,Object>> answers = new ArrayList<>();
        for (ExamPaperTitleItemVM title:titleItems) {
            for (QuestionEditRequestVM questionEditRequestVM:title.getQuestionItems()) {
                questionEditRequestVM.setScore("10");
                if (questionEditRequestVM.getQuestionType() == QuestionTypeEnum.TrueFalse.getCode()) {
                    questionEditRequestVM.setCorrect("对");
                    for (QuestionEditItemVM questionEditItemVM:questionEditRequestVM.getItems()) {
                        questionEditItemVM.setPrefix(questionEditItemVM.getContent());
                    }
                }
                if (questionEditRequestVM.getQuestionType() == QuestionTypeEnum.SingleChoice.getCode()) {
                    questionEditRequestVM.setCorrect("A.");
                }
                if (questionEditRequestVM.getQuestionType() == QuestionTypeEnum.MultipleChoice.getCode()) {
                    questionEditRequestVM.setCorrect(null);
                    questionEditRequestVM.setCorrectArray(Lists.newArrayList("A.","B."));
                }

                Map<String,Object> answerMap = new HashMap<>();
                answerMap.put("questionType",questionEditRequestVM.getQuestionType().toString());
                answerMap.put("questionTitle",questionEditRequestVM.getTitle());
                answerMap.put("questionCode", MD5Utils.encode(subjectCode + questionEditRequestVM.getTitle()));
                answerMap.put("answers",Lists.newArrayList("标准答案"));
                answers.add(answerMap);
            }
        }
        String path = "/Users/guiliangzhou/IdeaProjects/answer-tool/src/main/resources/" + subjectCode  + "/" + subjectCode + ".answer2";
        File file = new File(path);
        String json = JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat);
        FileUtils.writeStringToFile(file, json,"utf-8");

    }


    public static List<ExamPaperTitleItemVM> generate(String subjectCode) throws IOException {
        //section
        Map<String, LearnSection> sections = getSections(subjectCode);
        String paperPath = "/Users/guiliangzhou/IdeaProjects/answer-tool/src/main/resources/" + subjectCode + "/question2/";
        File file = new File(paperPath);
        if (!file.exists()) {
            throw new RuntimeException("文件路径不存在");
        }
        Collection<File> files = FileUtils.listFiles(file,null,false);
        Map<String,List<String>> titleMap = new TreeMap<>();
        Map<String,File> map = new HashMap<>();
        for (File file1:files) {
            String fileName = file1.getName();
            map.put(fileName,file1);
            String[] strs = fileName.split("-");
            String midCode = strs[0];
            List<String> titles = titleMap.getOrDefault(midCode,new ArrayList<>());
            titles.add(fileName);
            titleMap.put(midCode,titles);
        }
        for (Map.Entry<String,List<String>> entry:titleMap.entrySet()) {
            Collections.sort(entry.getValue());
        }

        List<ExamPaperTitleItemVM> titleItems = new ArrayList<>();
        for (Map.Entry<String,List<String>> entry:titleMap.entrySet()) {
            String midCode = entry.getKey();
            LearnSection section = sections.get(midCode);
            ExamPaperTitleItemVM titleItemVM = new ExamPaperTitleItemVM();
            titleItemVM.setName(section.getMidName());
            List<QuestionEditRequestVM> questions = new ArrayList<>();
            List<String> files2 = entry.getValue();
            for (String pathName:files2) {
                File questionFile = map.get(pathName);
                String str = FileUtils.readFileToString(questionFile,"utf-8");
                List<QuestionEditRequestVM> list = JSONObject.parseArray(str,QuestionEditRequestVM.class);
                int order = 1;
                for (QuestionEditRequestVM vm:list) {
                    vm.setItemOrder(order);
                    order++;
                }
                questions.addAll(list);
            }
            titleItemVM.setQuestionItems(questions);
            titleItems.add(titleItemVM);
        }
        return titleItems;
    }

    public static Map<String, LearnSection> getSections(String subjectCode) throws IOException {
        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +".section");
        List<String> lines = IOUtils.readLines(inputStream3);
        Map<String, LearnSection> map = new HashMap<>();
        for (String str:lines) {
            String[] strs = str.split(",");
            String url = strs[0].trim();
            String name = strs[1].trim();
            if (!url.contains("view")) {
                continue;
            }
            String midCode = url.split("id=")[1];
            String type = url.substring(url.indexOf("/mod") + 5,url.indexOf("/view"));

            LearnSection section = new LearnSection();
            section.setSubjectCode(subjectCode);
            section.setCreateUserId(4);
            section.setMidCode(midCode);
            section.setMidType(type);
            section.setMidOver(Byte.valueOf("0"));
            section.setMidName(name);
            section.setRequestUrl(url);
            map.put(midCode,section);
        }
        return map;
    }

}
